﻿using DevExpress.Blazor.DocumentMetadata;
using Localization.Resources.AbpUi;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using System.IO;
using System.Net.Http;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.Localization;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.AspNetCore.VirtualFileSystem;
using Volo.Abp.AuditLogging.EntityFrameworkCore;
using Volo.Abp.Autofac;
using Volo.Abp.AutoMapper;
using Volo.Abp.EntityFrameworkCore.SqlServer;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.UI.Navigation.Urls;
using Volo.Abp.VirtualFileSystem;
using WorkflowCore.Interface;
using Yhd.Captcha.Core.OtpNet;
using Zt.QmtqDemo.ConfmPlan.Saga;
using Zt.QmtqDemo.EntityFrameworkCore;
using Zt.QmtqDemo.Localization;
using Zt.QmtqDemo.MultiTenancy;

namespace Zt.QmtqDemo.Web
{
    [DependsOn(
        typeof(QmtqDemoHttpApiModule),
        typeof(QmtqDemoApplicationModule),
        typeof(QmtqDemoEntityFrameworkCoreDbMigrationsModule),
        typeof(AbpEntityFrameworkCoreSqlServerModule),
        typeof(AbpAuditLoggingEntityFrameworkCoreModule),
        typeof(AbpAutofacModule),
        typeof(AbpAspNetCoreSerilogModule)
        )]
    public class QmtqDemoWebModule : AbpModule
    {
        private IWorkflowHost workflowHost;

        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.PreConfigure<AbpMvcDataAnnotationsLocalizationOptions>(options =>
            {
                options.AddAssemblyResource(
                    typeof(QmtqDemoResource),
                    typeof(QmtqDemoDomainModule).Assembly,
                    typeof(QmtqDemoDomainSharedModule).Assembly,
                    typeof(QmtqDemoApplicationModule).Assembly,
                    typeof(QmtqDemoApplicationContractsModule).Assembly,
                    typeof(QmtqDemoWebModule).Assembly
                );
            });
        }

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration = context.Services.GetConfiguration();
#if DEBUG
            context.Services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
#endif
            context.Services.AddMvc(options => options.EnableEndpointRouting = false)
               .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            context.Services.AddRazorPages();
            context.Services.AddServerSideBlazor();

            ConfigureUrls(configuration);
            //ConfigureAuthentication(context, configuration);
            ConfigureAutoMapper();
            ConfigureVirtualFileSystem(hostingEnvironment);
            ConfigureLocalizationServices();
            ConfigureAutoApiControllers();
            ConfigureSwaggerServices(context.Services);

            context.Services.AddTransient<YhdTotp>(sp => new YhdTotp(120, totpSize:3));
            context.Services.AddDocumentMetadata((serviceProvider, registrator) => {
                DemoConfiguration config = serviceProvider.GetService<IOptions<DemoConfiguration>>().Value;
                config.RegisterPagesMetadata(registrator);
            });

            context.Services.AddDevExpressBlazor();
            ConfigureWorkflowcore(context);

            context.Services.AddHttpClient();
            context.Services.AddScoped<HttpClient>((sp) => {
                var httpClient = sp.GetService<IHttpClientFactory>().CreateClient();
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                return httpClient;
            });
        }

        private void ConfigureUrls(IConfiguration configuration)
        {
            Configure<AppUrlOptions>(options =>
            {
                options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
            });
        }

        private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddAuthentication()
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = false;
                    options.ApiName = "QmtqDemo";
                });
        }

        private void ConfigureAutoMapper()
        {
            Configure<AbpAutoMapperOptions>(options =>
            {
                options.AddMaps<QmtqDemoWebModule>();

            });
        }

        private void ConfigureVirtualFileSystem(IWebHostEnvironment hostingEnvironment)
        {
            if (hostingEnvironment.IsDevelopment())
            {
                Configure<AbpVirtualFileSystemOptions>(options =>
                {
                    options.FileSets.ReplaceEmbeddedByPhysical<QmtqDemoDomainSharedModule>(Path.Combine(hostingEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Zt.QmtqDemo.Domain.Shared"));
                    options.FileSets.ReplaceEmbeddedByPhysical<QmtqDemoDomainModule>(Path.Combine(hostingEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Zt.QmtqDemo.Domain"));
                    options.FileSets.ReplaceEmbeddedByPhysical<QmtqDemoApplicationContractsModule>(Path.Combine(hostingEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Zt.QmtqDemo.Application.Contracts"));
                    options.FileSets.ReplaceEmbeddedByPhysical<QmtqDemoApplicationModule>(Path.Combine(hostingEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Zt.QmtqDemo.Application"));
                    options.FileSets.ReplaceEmbeddedByPhysical<QmtqDemoWebModule>(hostingEnvironment.ContentRootPath);
                });
            }
            Configure<AbpVirtualFileSystemOptions>(options =>
            {
                options.FileSets.AddEmbedded<IServerSideBlazorBuilder>();
            });

            Configure<AbpAspNetCoreContentOptions>(options => {
                options.AllowedExtraWebContentFolders.Add("_framework");

            });

        }

        private void ConfigureLocalizationServices()
        {
            Configure<AbpLocalizationOptions>(options =>
            {
                options.Resources
                    .Get<QmtqDemoResource>()
                    .AddBaseTypes(
                        typeof(AbpUiResource)
                    );

                options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
                options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
                options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
            });
        }

        private void ConfigureAutoApiControllers()
        {
            Configure<AbpAspNetCoreMvcOptions>(options =>
            {
                options.ConventionalControllers.Create(typeof(QmtqDemoApplicationModule).Assembly);
            });
        }

        private void ConfigureSwaggerServices(IServiceCollection services)
        {
            services.AddSwaggerGen(
                options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo { Title = "QmtqDemo API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
                    options.CustomSchemaIds(type => type.FullName);
                }
            );
        }

        private static void ConfigureWorkflowcore(ServiceConfigurationContext context)
        {
            //context.Services.AddWorkflow();
            context.Services.AddWorkflow(x => x.UseSqlite(@"Data Source=database.db;", true));
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            app.UseCorrelationId();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseErrorPage();
            }
            app.UseStaticFiles();
            app.UseVirtualFiles();
            app.UseRouting();
            //app.UseAuthentication();
            //app.UseJwtTokenMiddleware();
            //app.UseIdentityServer();
            //app.UseAuthorization();
            app.UseAbpRequestLocalization();
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "QmtqDemo API");
            });
            //app.UseAuditing();
            app.UseAbpSerilogEnrichers();
            app.UseMvcWithDefaultRoute();

            app.UseEndpoints(endpoints => {
                endpoints.MapBlazorHub();
                endpoints.MapRazorPages();
                endpoints.MapFallbackToPage("/_Host");
            });
        }


        public override void OnPostApplicationInitialization(ApplicationInitializationContext context)
        {
            workflowHost = context.ServiceProvider.GetService<IWorkflowHost>();
            workflowHost.RegisterWorkflow<ConfmPlanWorkflow, ConfPlanData>();
            workflowHost.Start();
        }

        public override void OnApplicationShutdown(ApplicationShutdownContext context)
        {
            workflowHost.Stop();
        }
    }
}
